// packageA/member/supplier/SupplierShop3/index.js
let app = getApp();
const skinBehavior = require('../../../../utils/themeSkin/skinBehavior');
Page({
  behaviors: [skinBehavior],
  /**
   * 页面的初始数据
   */
  data: {
    districtVal: '',
    strShow: false,
    provinceData: [],
    pickerValue: [0, 0, 0],
    point: {},
    showChangeAdrr: false,


    imgPath: app.globalData.imgPath,
    active: 0,
    supplierInfo: {
      supplier_info: {},
      slide_list: [],
      category_subarea: [],
      button_list: []
    },
    CategoryList: [],
    goodsArr: [],

    showCarList: false,
    cartsNum: 0,
    cartsTotal: 0,
    cart_ids: [],
    carList: [],
    goodsCartsTotal: [],
    popupSpecs: false,
    goodinfo: {},
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    if (options.id) {
      this.supplierid = options.id;
      this.initPage();
    } else {
      this.setData({
        showChangeAdrr: true
      })
      wx.getStorage({
        key: 'RegionSuppliersID',
        success: (res) => {
          this.supplierid = res.data;
          this.initPage();
        },
        fail: () => {
          this._initAddressInfo();
        }
      })
    }
  },
  onClickVal(e) {
    let {
      name,
      val
    } = e.currentTarget.dataset;
    this.setData({
      [name]: val
    });
  },
  toUrl(e) {
    let {url} = e.currentTarget.dataset || {};
    wx.navigateTo({
      url: url,
      fail: ()=> {
        wx.reLaunch({
          url: url
        });
      }
    });
  },

  initPage() {
    this.getData();
    this.getCar();
  },
  onSelectSup(e) {
    let {
      id
    } = e.currentTarget.dataset;
    this.supplierid = id;
    this.initPage();
    this.setData({
      SupplierListPop: false
    });
    wx.setStorage({
      key: "RegionSuppliersID",
      data: id
    })
  },

  async getData() {
    let urlStr = app.getNetAddresss('plugin.supplier-shop-three.frontend.index.index');
    let response = await app._postNetWork({
      url: urlStr,
      data: {
        supplier_id: this.supplierid
      }
    });
    let {
      result,
      msg,
      data
    } = response.data;
    if (!result) return app.tips(msg);
    let {supplier_info, slide_list, category_subarea,button_list,background} = data;
    if(!background){
      wx.setNavigationBarColor({
        frontColor: '#ffffff',
        backgroundColor: this.data.themeBaseColor
      });
    }
    let _this = {
      supplierInfo: {}
    };
    _this.supplierInfo.supplier_info = supplier_info;
    _this.supplierInfo.slide_list = slide_list;
    _this.supplierInfo.category_subarea = category_subarea;
    _this.supplierInfo.button_list = button_list;
    _this.topbackground = background;
    this.setData(_this);
  },
  
  onClickTab(event) {
    this.setData({
      active: event.detail.name
    })
    if (event.detail.name == 1) {
      this.getGoodsData();
    }
  },
  async getGoodsData() {
    let urlStr = app.getNetAddresss('plugin.supplier-shop-three.frontend.index.all-goods');
    let response = await app._postNetWork({
      url: urlStr,
      data: {
        supplier_id: this.supplierid
      }
    });
    let {
      result,
      msg,
      data
    } = response.data;
    if (!result) return app.tips(msg);
    this.setData({
      goodsArr: data.data
    })
  },
  async getCar() {
    let urlStr = app.getNetAddresss('plugin.supplier-shop-three.frontend.member-cart.index');
    let response = await app._postNetWork({
      url: urlStr,
      data: {
        supplier_id: this.supplierid
      }
    });
    let {
      result,
      msg,
      data
    } = response.data;
    if (!result) return app.tips(msg);

    //获取 data.list数组里merchant_id的值为this.$route.params.id的数据
    // let carList = data.list.filter(item => item.merchant_id == this.supplierid);
    let carList = data.list;
    if(!carList.length) return;
    this.setData({
      carList: carList
    })
    this.getFirstCart(carList);
  },
  //统计购物车的总价格和总数量
  getFirstCart(data) {
    this.data.carts = data;
    let cartsNum = 0;
    let cartsTotal = 0;
    this.data.carts.forEach((item) => {
      cartsNum += item.total;
      cartsTotal += item.total * item.goods_price;
    });
    cartsTotal = parseFloat(cartsTotal).toFixed(2);
    this.setData({
      cartsNum,
      cartsTotal,
    });
    this.calculateTotal(this.data.carts);
  },
  //不同规格的同一商品求和
  calculateTotal(arr) {
    let temp = {};
    for (let i in arr) {
      let key = arr[i].goods_id;
      this.data.cart_ids.push(arr[i].id);
      if (temp[key]) {
        // temp[key].goods_id = temp[key].goods_id;
        temp[key].total = temp[key].total + arr[i].total;
      } else {
        temp[key] = {};
        temp[key].goods_id = arr[i].goods_id;
        temp[key].total = arr[i].total;
        temp[key].id = arr[i].id;
      }
    }
    this.setData({
      goodsCartsTotal: temp,
    });
  },
  async showGoodPup(e) {
    let _id = e.currentTarget.dataset.id;
    if (this.activity_gid == _id) {
      this.setData({
        popupSpecs: true
      });
      return;
    }
    this.activity_gid = _id;
    let urlStr = app.getNetAddresss('goods.goods.get-goods-page');
    let response = await app._postNetWork({
      url: urlStr,
      data: {
        id: Number(_id)
      }
    });
    let {
      result,
      msg,
      data
    } = response.data;
    if (!result) return app.tips(msg);
    this.setData({
      goodinfo: data.get_goods,
      popupSpecs: true
    });
  },
  close_yz_specs_popup(e) {
    console.log(e);
    if (e.detail.clicktype == 1) {
      //点击确认按钮
      // if (id) {
      //   // 有购物车记录
      //   this.updateCart(id, goodsCount);
      // } else {
      // 新加入购物车
      this.addCart(this.activity_gid, e.detail.goodsCount, e.detail.optionsId);
      // }
    }
    this.setData({
      popupSpecs: false,
    });
  },
  async addCart(gid, total, option_id) {
    let urlStr = app.getNetAddresss('plugin.supplier-shop-three.frontend.member-cart.store');
    let response = await app._postNetWork({
      url: urlStr,
      data: {
        goods_id: gid,
        total: total,
        option_id: option_id,
        supplier_id: this.supplierid
      }
    });
    let {
      result,
      msg,
      data
    } = response.data;
    if (!result) return app.tips(msg);
    this.getCar();
  },
  onChangeCartListPopup() {
    this.setData({
      showCarList: !this.data.showCarList,
    });
  },
  addGoods(e) {
    let {
      id,
      total
    } = e.detail;
    this.updateCart(id, total + 1);
  },
  reduceGoods(e) {
    let {
      id,
      total
    } = e.detail;
    this.updateCart(id, total - 1);
  },
  blurCart(e) {
    let {
      id,
      total
    } = e.detail;
    this.updateCart(id, total);
  },
  async updateCart(id, num) {
    let json = {
      num: num,
      id: id,
      supplier_id: this.supplierid
    };
    let _url = "plugin.supplier-shop-three.frontend.member-cart.updateNumV2";
    if (num == 0) {
      _url = "plugin.supplier-shop-three.frontend.member-cart.destroy";
      json = {
        ids: id,
        supplier_id: this.supplierid
      };
    }
    let urlStr = app.getNetAddresss(_url);
    let response = await app._postNetWork({
      url: urlStr,
      data: json
    });
    let {
      result,
      msg,
      data
    } = response.data;
    this.getCar();
  },
  checkGoods() {
    if (this.data.cartsNum == 0) {
      return app.tips("购物车为空");
    }
    wx.navigateTo({
      url: "/packageD/buy/myOrder_v2/myOrder_v2?tag=suppThreeCart&cart_ids=" + JSON.stringify(this.data.cart_ids)
    });
  },
  toSearch(e) {
    let {
      id
    } = e.currentTarget.dataset;
    if(id === 0) {
      this.setData({
        active: 1
      })
      return;
    }
    wx.navigateTo({
      url: '/packageA/member/supplier/SupplierSearch/SupplierSearch?id=' + this.supplierid + 'cid=' + id,
    });
  },
  clearCart(){
    wx.showModal({
      title: '提示',
      content: '确定清空购物车吗?',
      success: (res)=> {
        if (res.confirm) {
          this.clearCartAction();
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },
  async clearCartAction() {
    let urlStr = app.getNetAddresss('plugin.supplier-shop-three.frontend.member-cart.allDestroy');
    let response = await app._postNetWork({
      url: urlStr,
      data: {
        supplier_id: this.supplierid
      }
    });
    let {
      result,
      msg,
      data
    } = response.data;
    if (!result) return app.tips(msg);
    this.getCar();
  },
  showGoodDetail(e){
    let {
      id
    } = e.currentTarget.dataset;
    wx.navigateTo({
      url: '/packageA/detail_v2/detail_v2?id=' + id,
    });
  },

  //  处理地址选择 -----------------------------
  //地址选择器数据初始化
  _initAddressInfo: function () {
    var that = this;
    var _keyName = 'provinceData';
    wx.getStorage({
      key: _keyName,
      success: function (res) {
        console.log("地址信息准备就绪");
        that._getProvinceData();
      },
      fail: function (res) {
        console.log("省fail");
        app._getNetWork({
          url: app.getNetAddresss("member.member-address.address"),
          success: function (res) {
            var response = res.data;
            var province = response.data.province;
            var city = response.data.city;
            var district = response.data.district;
            wx.setStorage({
              key: 'provinceData',
              data: province
            });
            wx.setStorage({
              key: 'cityData',
              data: city
            });
            wx.setStorage({
              key: 'districtData',
              data: district
            });
            that._initAddressInfo();
          },
          fail: function (res) {},
          state: true
        });
      }
    });
  },
  // 读取省key
  _getProvinceData: function () {
    var that = this;
    var _keyName = 'provinceData';
    wx.getStorage({
      key: _keyName,
      success: function (res) {
        that.setData({
          provinceData: res.data,
        });
        that.setData({
          "selectAddressData[0].name": res.data[that.data.pickerValue[0]].areaname,
          "selectAddressData[0].id": res.data[that.data.pickerValue[0]].id,
          "selectAddressData[0].index": that.data.pickerValue[0]
        });
        that._getCityData();
      }
    });
  },
  // 读取城市key，筛选城市data
  _getCityData: function () {
    var _data = this.data.selectAddressData[0];
    var that = this;
    var _keyName = 'cityData';
    wx.getStorage({
      key: _keyName,
      success: function (res) {
        var _json = [];
        for (var i = 0; i < res.data.length; i++) {
          if (res.data[i].parentid == _data.id) {
            _json.push(res.data[i]);
          }
        }
        that.setData({
          cityData: _json,
          openDateLw: true
        });
        that.setData({
          "selectAddressData[1].name": _json[that.data.pickerValue[1]].areaname,
          "selectAddressData[1].id": _json[that.data.pickerValue[1]].id,
          "selectAddressData[1].index": that.data.pickerValue[1]
        });
        that._getDistrictData();
      }
    });
  },
  // 读取地区key，筛选地区data
  _getDistrictData: function () {
    var _data = this.data.selectAddressData[1];
    var that = this;
    var _keyName = 'districtData';
    wx.getStorage({
      key: _keyName,
      success: function (res) {
        var _json = [];
        for (var i = 0; i < res.data.length; i++) {
          if (res.data[i].parentid == _data.id) {
            _json.push(res.data[i]);
          }
        }
        that.setData({
          districtData: _json
        });
        that.setData({
          "selectAddressData[2].name": _json[that.data.pickerValue[2]].areaname,
          "selectAddressData[2].id": _json[that.data.pickerValue[2]].id,
          "selectAddressData[2].index": that.data.pickerValue[2]
        });
      }
    });
  },
  // 收货地址滚动事件
  bindChange: function (e) {
    var val = e.detail.value;
    if (this.data.pickerValue[0] != val[0]) {
      val[1] = 0;
      val[2] = 0;
    }
    if (this.data.pickerValue[1] != val[1]) {
      val[2] = 0;
    }
    this.setData({
      "pickerValue[0]": val[0],
      "pickerValue[1]": val[1],
      "pickerValue[2]": val[2]
    });
    this._initAddressInfo();
  },
  // 确定选择收货地址
  _okAddress: function () {
    let seleData = this.data.selectAddressData;
    this.setData({
      "form.street": "",
      "districtVal": "",
      "addressName": seleData[0].name + ' ' + seleData[1].name + ' ' + seleData[2].name,
      "form.province": seleData[0].name,
      "form.city": seleData[1].name,
      "form.district": seleData[2].name
    });

    this.province_id = seleData[0].id;
    this.city_id = seleData[1].id;
    this.district_id = seleData[2].id;

    this._getStreet(seleData[2].id);
    this._closeDateLw();
  },
  // 关闭选择收货地址
  _closeDateLw: function () {
    this.setData({
      openDateLw: false
    });
  },
  //获取街道
  _getStreet(param, key = '') {
    let that = this;
    let urlStr = app.getNetAddresss("member.memberAddress.street");
    urlStr += "&district_id=" + param;
    app._getNetWork({
      url: urlStr,
      success: function (resdata) {
        var res = resdata.data;
        if (res.result == 1 && !app._isTextEmpty(res.data)) {
          if (!app._isTextEmpty(res.data) && res.data.length > 0) {
            that.setData({
              districtVal: res.data,
              streetShow: true
            });
          }
        } else {
          // 没有街道，直接搜索当地供应商列表
          this.addressGeocoder();
        }
      },
      fail: function (res) {
        console.log(res);
      }
    });
  },
  streetConfirm(e) {
    let {strname,id} = e.target.dataset;
    this.setData({
      "form.street": strname,
      "streetShow": false,
    });
    this.street_id = id;
    this.getSupplierData();
    // this.setData({
    //   SupplierList: [],
    //   SupplierListPop: true
    // })
  },
  async getSupplierData() {
    if(this.getSupplierData_finished) return;
    let urlStr = app.getNetAddresss('plugin.supplier-shop-three.frontend.preposition.get-district-supplier-list');
    let response = await app._postNetWork({
      url: urlStr,
      data: {
        page: this.getSupplierDataPage || 1,
        province_id: this.province_id,
        city_id: this.city_id,
        district_id: this.district_id,
        street_id: this.street_id || 0
      }
    });
    let {
      result,
      msg,
      data
    } = response.data;
    if (!result) return app.tips(msg);
    this.setData({
      SupplierList: data.data,
      SupplierListPop: true
    })
    if(data.current_page == data.last_page) {
      return this.getSupplierData_finished = true;
    }
    this.getSupplierDataPage = data.current_page + 1;
  },
  onChangeAress(){
    this.getSupplierData_finished = false;
    this.getSupplierDataPage = 1;
    this._initAddressInfo();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})